package com.shaoshaohuo.app.ui.ec;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.EcCategorySecond;
import com.shaoshaohuo.app.entity.EcCategoryThird;
import com.shaoshaohuo.app.entity.EcVarietyEntity;
import com.shaoshaohuo.app.entity.PurchaseHall;
import com.shaoshaohuo.app.entity.PurchaseHallEntity;
import com.shaoshaohuo.app.entity.SupplyRecord;
import com.shaoshaohuo.app.entity.SupplyRecordEntity;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.adapter.DumpGoodsAdapter;
import com.shaoshaohuo.app.adapter.PurchaseListAdapter;
import com.shaoshaohuo.app.view.SelectProductTypePop;
import com.shaoshaohuo.app.view.SelectProductTypePop.OnSelectItemListener;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.XListView.IXListViewListener;
import com.shaoshaohuo.app.utils.CityinfoUtil;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.citymenu.entity.Area;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SeasonHotActivity
 * @author linmu
 * @Decription 当季热销
 * @2015-8-28 下午9:47:05
 */
public class SeasonHotActivity extends BaseActivity implements OnClickListener, IXListViewListener {

	private static final int SELECT_PRODUCT_TYPE = 1;
	private static final int SELECT_MARKET_CITY = SELECT_PRODUCT_TYPE + 1;
	
	private TopbarView mTopbarView;

	private TextView mLeftTabText;
	private TextView mRightTabText;
	
	private TextView mAreaText;
	private TextView mTypeText;

	private XListView mGongyingListView;
	private XListView mCaigouListView;

	private PurchaseListAdapter<PurchaseHall> mPurchaseAdapter;
	private List<PurchaseHall> mPurchaseDataList = new ArrayList<PurchaseHall>();
	
	private String title = "";
//	private String bigpid = "";
//	private String pid = "";
//	private String catid = "";
	
	private String varieties = "";
	private String cityid = "";
	private String action = ListViewAction.NEW;
	private String cursor = "0";
	private int size = 10;
	
	private Cityinfo selectCity;
	
	private DumpGoodsAdapter<SupplyRecord> mAdapter;

	private List<SupplyRecord> mSupplyDataList = new ArrayList<SupplyRecord>();
	private String bigpid = "";
	private String catid = "";
	private String pid = "";
	
	
	private String action1 = ListViewAction.NEW2;
	private String cursor1 = "0";
	private int offset1 = 10;
	private String shuai = "0";
	
	private boolean isSupplyStatus = true;
	private EcCategorySecond ecCategorySecond;
	private CascadingMenuPopWindow cascadingMenuPopWindow;
	protected List<EcCategoryThird> mVarietyList;
	private SelectProductTypePop selectProductTypePop;
	
	private boolean isSupply = true;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(new TopbarView(this));
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                setContentView(R.layout.activity_season_hot);
                initData();
                initView();
                setUpView();
                getVariety();
            }
        }, 200);
	}
	
	private void getVariety() {
		startLoadingDialog();
		RequestService.getInstance().getEcCategoryVariety(this, bigpid, pid, EcVarietyEntity.class,
				new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							EcVarietyEntity entity = (EcVarietyEntity) resultData;
							// setVarietyAdapter(entity.getData().getList());
							mVarietyList = entity.getData().getList();
						} else {
							showToast(resultData.getMsg());
						}
					}

					@Override
					public void onFailed(int requestCode, Exception error, String msg) {
						dismissLoadingDialog();
						showToast(R.string.please_check_network);
					}
				});
	}

	protected void initData() {
		Intent intent = getIntent();
		bigpid = intent.getStringExtra(ExtraName.bigpid);
		pid = intent.getStringExtra(ExtraName.catid);
		title = intent.getStringExtra(ExtraName.title);
		isSupply = intent.getBooleanExtra(ExtraName.isSupply,true);
//	    intent.putExtra(ExtraName.bigpid, item.getBigpid());
//        intent.putExtra(ExtraName.catid, item.getCatid());
//        intent.putExtra(ExtraName.title, item.getTitle());
	    
    }

    private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mLeftTabText = (TextView) this.findViewById(R.id.textview_tab_left);
		mRightTabText = (TextView) this.findViewById(R.id.textview_tab_right);

		mGongyingListView = (XListView) this.findViewById(R.id.listview_gongying_list);
		mCaigouListView = (XListView) this.findViewById(R.id.listview_caigou_list);
		
		mAreaText = (TextView) this.findViewById(R.id.textview_tab_diqu);
		mTypeText = (TextView) this.findViewById(R.id.textview_tab_pinzhong);
	}

	private void setUpView() {
		mTopbarView.setCenterText("当季热销");
		mTopbarView.setLeftView(true, true);

		mLeftTabText.setOnClickListener(this);
		mRightTabText.setOnClickListener(this);
		mAreaText.setOnClickListener(this);
		mTypeText.setOnClickListener(this);

//		mTypeText.setText(title);
		
		startLoadingDialog();
		if(isSupply){
			onClick(mLeftTabText);
		}else{
			onClick(mRightTabText);
		}
		setSuppyListView();
		setPurchaseListView();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textview_tab_left:
			if (mLeftTabText.isSelected()) {
				return;
			}
			mLeftTabText.setSelected(true);
			mRightTabText.setSelected(false);
			isSupplyStatus = true;
			changeState();
//			if(mSupplyDataList.isEmpty()){
//				getSupplyData(true);
				refrensh();
//			}
			break;
		case R.id.textview_tab_right:
			if (mRightTabText.isSelected()) {
				return;
			}
			mLeftTabText.setSelected(false);
			mRightTabText.setSelected(true);
			isSupplyStatus = false;
			changeState();
//			if(mPurchaseDataList.isEmpty()){
//				getCaigouData(false);
			refrensh();
//			}
			break;
		case R.id.textview_tab_diqu:
			selectMarketCity();
			break;
		case R.id.textview_tab_pinzhong:
//			selectProduct();
			if(mVarietyList == null || mVarietyList.isEmpty()){
				showToast("暂无品种可选");
				return;
			}
			if (selectProductTypePop == null) {

				selectProductTypePop = new SelectProductTypePop(this);
				selectProductTypePop.setOnSelectItemListener(new OnSelectItemListener() {

					@Override
					public void onSelect(List<EcCategoryThird> list) {
						StringBuilder sb = new StringBuilder();
						for (EcCategoryThird item : list) {
							sb.append(item.getPid() + ",");
						}
						if(isSupplyStatus){
							catid = sb.toString();
						}else{
							varieties = sb.toString();
						}
						refrensh();
					}
				});
			}
			selectProductTypePop.setData(mVarietyList);
			selectProductTypePop.showLocation(mLeftTabText);
			break;
		}
	}

	private void selectMarketCity() {
        /*Intent intent = new Intent(this,SelectProvinceActivity.class);
        startActivityForResult(intent, SELECT_MARKET_CITY);*/
//		new CascadingMenuPopWindow().showInstance(this, mRightTabText, new NMCascadingMenuViewOnSelectListener());
		if (cascadingMenuPopWindow == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindow = new CascadingMenuPopWindow(this);
			cascadingMenuPopWindow
					.setMenuViewOnSelectListener(new NMCascadingMenuViewOnSelectListener());
			cascadingMenuPopWindow.showAsDropDown(mRightTabText, 5, 5);
		} else if (cascadingMenuPopWindow != null
				&& cascadingMenuPopWindow.isShowing()) {
			cascadingMenuPopWindow.dismiss();
		} else {
			cascadingMenuPopWindow.showAsDropDown(mRightTabText, 5, 5);
		}
    }
	
	class NMCascadingMenuViewOnSelectListener implements
			CascadingMenuViewOnSelectListener {

		@Override
		public void getValue(Area city, String fullname) {
			selectCity = CityinfoUtil.convert(city);
			if (selectCity == null) {
				mAreaText.setText(fullname);
			} else {
				mAreaText.setText(selectCity.getCity_name());
			}
			refrensh();
		}

	}
	
	private void selectProduct() {
		Intent intent = new Intent(this, ProductTypeActivity.class);
		startActivityForResult(intent, SELECT_PRODUCT_TYPE);
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case SELECT_PRODUCT_TYPE:
                EcCategorySecond second = (EcCategorySecond) data.getSerializableExtra(ExtraName.ecCategorySecond);
                if(ecCategorySecond != null && !TextUtils.isEmpty(ecCategorySecond.getCatid()) && ecCategorySecond.getCatid().equals(second.getCatid())){
                }else{
                	
                	if(ecCategorySecond != null && second.getCatname().equals("全部") && ecCategorySecond.getCatname().equals("全部") ){
                		return;
                	}
                    ecCategorySecond = second;
                    bigpid = ecCategorySecond.getBigpid();
                    catid = ecCategorySecond.getCatid();
                    mTypeText.setText(ecCategorySecond.getCatname());
                    refrensh();
                }  
                break;
            case SELECT_MARKET_CITY:
//                selectProvince = (Province) Data.getSerializableExtra(ExtraName.province);
//                selectCity = (City) Data.getSerializableExtra(ExtraName.city);
//                mAreaText.setText(selectCity.getCityname());
//                refrensh();
                break;
            }
        }
    }
	
	private void changeState() {
		if (mLeftTabText.isSelected()) {
			mGongyingListView.setVisibility(View.VISIBLE);
			mCaigouListView.setVisibility(View.GONE);
		} else {
			mGongyingListView.setVisibility(View.GONE);
			mCaigouListView.setVisibility(View.VISIBLE);
		}
	}

	private void refrensh() {
		if(isSupplyStatus){
			mSupplyDataList.clear();
		}else{
			mPurchaseDataList.clear();
		}
		onRefresh();
	}
	
	private void getCaigouData(boolean isLoading) {
		if (isLoading) {
			startLoadingDialog();
		}
		if (selectCity != null) {
			cityid = selectCity.getId();
		} else {
			cityid = null;
		}
		
		RequestService.getInstance().getPurchaseList(this, cursor, size+"", action, bigpid, pid, varieties, cityid, PurchaseHallEntity.class,
				new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							PurchaseHallEntity entity = (PurchaseHallEntity) resultData;
							List<PurchaseHall> list = entity.getData().getList();
							mPurchaseDataList.addAll(list);

							if ((mPurchaseDataList.size() < size) || (action.equals(ListViewAction.HISTORY) && list.size() < size)) {
								// mCaigouListView.setPullLoadEnable(false);
								mCaigouListView.endLoadingMore("没有更多了");
							}
							setPurchaseAdapter(mPurchaseDataList);

						} else {
							showToast(resultData.getMsg());
						}
						onLoad();
					}

					@Override
					public void onFailed(int requestCode, Exception error, String msg) {
						dismissLoadingDialog();
						showToast(msg);
						onLoad();
					}
				});
	}

	protected void setPurchaseAdapter(List<PurchaseHall> mDataList2) {
		if (mPurchaseAdapter == null) {
			mPurchaseAdapter = new PurchaseListAdapter<PurchaseHall>(this, mDataList2, false);
			mCaigouListView.setAdapter(mPurchaseAdapter);
		} else {
			mPurchaseAdapter.setData(mDataList2);
//			mPurchaseAdapter.notifyDataSetChanged();
		}
	}

	private void setPurchaseListView() {
		mCaigouListView.setPullLoadEnable(true);
		mCaigouListView.setPullRefreshEnable(true);
		mCaigouListView.setXListViewListener(this);

		mCaigouListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// PurchaseHall order = (Order)
				// parent.getItemAtPosition(position);
				// Intent intent = new
				// Intent(PurchaseHallActivity.this,OrderDetailShipperActivity.class);
				// intent.putExtra(ExtraName.orderid, order.getBusinessorderid());
				// startActivity(intent);
				PurchaseHall supply = (PurchaseHall) parent.getItemAtPosition(position);
				Intent intent = new Intent(SeasonHotActivity.this, PurchaseDetailActivity.class);
				intent.putExtra(ExtraName.id, supply.getId());
				startActivity(intent);
			}
		});
	}

	@Override
	public void onRefresh() {
		if(isSupplyStatus){
//			if (mSupplyDataList.size() > 0) {
//				cursor1 = mSupplyDataList.get(0).getCursor();
//			} else {
				cursor1 = "0";
//			}
				mSupplyDataList.clear();
			action1 = ListViewAction.NEW2;
			mGongyingListView.setPullLoadEnable(true);
			getSupplyData(false);
		}else{
//			if (mPurchaseDataList.size() > 0) {
//				cursor = mPurchaseDataList.get(0).getCursor();
//			} else {
				cursor = "0";
//			}
				mPurchaseDataList.clear();
			action = ListViewAction.NEW;
			mCaigouListView.setPullLoadEnable(true);
			getCaigouData(false);
		}
	}

	@Override
	public void onLoadMore() {
		if(isSupplyStatus){
			if (mSupplyDataList.size() > 0) {
				cursor1 = mSupplyDataList.get(mSupplyDataList.size() - 1).getCursor();
			} else {
				cursor1 = "0";
			}
			action1 = ListViewAction.HISTORY2;
			getSupplyData(false);
		}else{
			if (mPurchaseDataList.size() > 0) {
				cursor = mPurchaseDataList.get(mPurchaseDataList.size() - 1).getCursor();
			} else {
				cursor = "0";
			}
			action = ListViewAction.HISTORY;
			getCaigouData(false);
		}
	}

	private void onLoad() {
		if(isSupplyStatus){
			mGongyingListView.stopRefresh();
			mGongyingListView.stopLoadMore();
		}else{
			mCaigouListView.stopRefresh();
			mCaigouListView.stopLoadMore();
		}
	}
	
	private void getSupplyData(boolean isLoading) {
		if (isLoading) {
			startLoadingDialog();
		}
		if (selectCity != null) {
			cityid = selectCity.getId();
		} else {
			cityid = null;
		}
		
//		RequestService.getInstance().supplyPublishList(this, "", "","","","","","","", SupplyRecordEntity.class,
		RequestService.getInstance().supplyPublishList(this, cursor1, offset1+"", action1, bigpid, pid, catid, cityid,shuai, SupplyRecordEntity.class,
				new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							SupplyRecordEntity entity = (SupplyRecordEntity) resultData;
							List<SupplyRecord> list = entity.getData().getList();
							mSupplyDataList.addAll(list);

							if ((mSupplyDataList.size() < offset1) || (action.equals(ListViewAction.HISTORY2) && list.size() < offset1)) {
								// mGongyingListView.setPullLoadEnable(false);
								mGongyingListView.endLoadingMore("没有更多了");
							}
							setAdapter(mSupplyDataList);

						} else {
							showToast(resultData.getMsg());
						}
						onLoad();
					}

					@Override
					public void onFailed(int requestCode, Exception error, String msg) {
						dismissLoadingDialog();
						showToast(msg);
						onLoad();
					}
				});
	}

	protected void setAdapter(List<SupplyRecord> mDataList2) {
		if (mAdapter == null) {
			mAdapter = new DumpGoodsAdapter<SupplyRecord>(this, mDataList2, false);
			mGongyingListView.setAdapter(mAdapter);
		} else {
			mAdapter.setData(mDataList2);
		}
	}

	private void setSuppyListView() {
		mGongyingListView.setPullLoadEnable(true);
		mGongyingListView.setPullRefreshEnable(true);
		mGongyingListView.setXListViewListener(this);

		mGongyingListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// PurchaseRecord order = (Order)
				// parent.getItemAtPosition(position);
				// Intent intent = new
				// Intent(PurchaseRecordActivity.this,OrderDetailShipperActivity.class);
				// intent.putExtra(ExtraName.orderid, order.getBusinessorderid());
				// startActivity(intent);
				SupplyRecord supply = (SupplyRecord) parent.getItemAtPosition(position);
				Intent intent = new Intent(SeasonHotActivity.this, SupplyDetailActivity.class);
				intent.putExtra(ExtraName.id, supply.getId());
				startActivity(intent);
			}
		});
	}
	@Override
	protected void onDestroy() {
		if (cascadingMenuPopWindow != null) {
			cascadingMenuPopWindow.dismiss();
		}
		super.onDestroy();
	}
}
